package com.xinan.weixin;

import com.jfinal.aop.ClearInterceptor;
import com.jfinal.log.Logger;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.MenuApi;
import com.jfinal.weixin.sdk.jfinal.WeixinController;
import com.jfinal.weixin.sdk.msg.in.InImageMsg;
import com.jfinal.weixin.sdk.msg.in.InLinkMsg;
import com.jfinal.weixin.sdk.msg.in.InLocationMsg;
import com.jfinal.weixin.sdk.msg.in.InTextMsg;
import com.jfinal.weixin.sdk.msg.in.InVideoMsg;
import com.jfinal.weixin.sdk.msg.in.InVoiceMsg;
import com.jfinal.weixin.sdk.msg.in.event.InFollowEvent;
import com.jfinal.weixin.sdk.msg.in.event.InLocationEvent;
import com.jfinal.weixin.sdk.msg.in.event.InMenuEvent;
import com.jfinal.weixin.sdk.msg.in.event.InQrCodeEvent;
import com.jfinal.weixin.sdk.msg.in.speech_recognition.InSpeechRecognitionResults;
import com.jfinal.weixin.sdk.msg.out.OutImageMsg;
import com.jfinal.weixin.sdk.msg.out.OutNewsMsg;
import com.jfinal.weixin.sdk.msg.out.OutTextMsg;
import com.jfinal.weixin.sdk.msg.out.OutVoiceMsg;
import com.xinan.utils.PropertiesHelper;
import com.xinan.weixin.in.InMassMsg;
import com.xinan.weixin.msg.WxMessage;

import java.util.*;



/**
 * 将此 DemoController 在YourJFinalConfig 中注册路由，
 * 并设置好weixin开发者中心的 URL 与 token ，使 URL 指向该
 * DemoController 继承自父类 WeixinController 的 index
 * 方法即可直接运行看效果，在此基础之上修改相关的方法即可进行实际项目开发
 */
@ClearInterceptor()
public class DemosController extends WeixinController {

    private static String urls = "";

    /**
     * 判断filePhth路径中是否存在该文件夹，不存在则创建该文件夹 创建成功则返回True
     *
     * @param filePhth
     * @return
     **/
    static {
        Properties r = PropertiesHelper.loadProperty("/weixin.properties");
        if (!r.isEmpty()) {
            try {
                urls = r.getProperty("wxmediaUrl");
                if (!urls.endsWith("/"))
                    urls = urls + "/";
            } catch (Exception e) {
                Logger.getLogger(DemosController.class).error("无法读取参数", e);
            }
        } else {
            Logger.getLogger(DemosController.class).error("无法读取 weixin.properties");
        }
    }


    /**
     * 实现父类抽方法，处理文本消息
     * 本例子中根据消息中的不同文本内容分别做出了不同的响应，同时也是为了测试 jfinal weixin sdk的基本功能：
     * 本方法仅测试了 OutTextMsg、OutNewsMsg、OutMusicMsg 三种类型的OutMsg，
     * 其它类型的消息会在随后的方法中进行测试
     */
    protected void processInMess(InMassMsg inMass) {

    }

    protected void processInTextMsg(InTextMsg inTextMsg) {
        String msgContent = inTextMsg.getContent().trim();
        String msgType = inTextMsg.getMsgType();
        inTextMsg.getFromUserName();
        System.out.println(inTextMsg.getContent());
        Record wMsg = wMessage(msgContent);
        //返回列表信息
        if (wMsg != null) {
            String msgtype = (String) wMsg.get("msgtype"); // 回复文本类型
            String description = (String) wMsg.get("description"); // 关键字
            String url = (String) wMsg.get("url"); // 消息链接
            String picurl = (String) wMsg.get("picurl"); // 消息图片
            String title = (String) wMsg.get("title"); // 标题
            String content = (String) wMsg.get("content"); // 文本内容
            if(picurl !=null) {
                picurl=urls.substring(0,urls.length()-1)+  picurl;
            }
            // 文本消息
            if (msgtype.equals("text")) {
                OutTextMsg outMsg = new OutTextMsg(inTextMsg);
                outMsg.setContent(content);
                render(outMsg);
                // 图文消息
            } else if (msgtype.equals("news")) {
                OutNewsMsg outMsg = new OutNewsMsg(inTextMsg);
                outMsg.addNews(title, "", picurl, url);
                render(outMsg);
                // 语音消息
            }
        }

    }

    /**
     * 实现父类抽方法，处理图片消息
     */
    protected void processInImageMsg(InImageMsg inImageMsg) {
        OutImageMsg outMsg = new OutImageMsg(inImageMsg);
        // 将刚发过来的图片再发回去
        outMsg.setMediaId(inImageMsg.getMediaId());
        render(outMsg);
    }

    /**
     * 实现父类抽方法，处理语音消息
     */
    protected void processInVoiceMsg(InVoiceMsg inVoiceMsg) {
        OutVoiceMsg outMsg = new OutVoiceMsg(inVoiceMsg);
        // 将刚发过来的语音再发回去
        outMsg.setMediaId(inVoiceMsg.getMediaId());
        render(outMsg);
    }

    /**
     * 实现父类抽方法，处理视频消息
     */
    protected void processInVideoMsg(InVideoMsg inVideoMsg) {
        /* 腾讯 api 有 bug，无法回复视频消息，暂时回复文本消息代码测试
		OutVideoMsg outMsg = new OutVideoMsg(inVideoMsg);
		outMsg.setTitle("OutVideoMsg 发送");
		outMsg.setDescription("刚刚发来的视频再发回去");
		// 将刚发过来的视频再发回去，经测试证明是腾讯官方的 api 有 bug，待 api bug 却除后再试
		outMsg.setMediaId(inVideoMsg.getMediaId());
		render(outMsg);
		*/
        OutTextMsg outMsg = new OutTextMsg(inVideoMsg);
        outMsg.setContent("\t视频消息已成功接收，该视频的 mediaId 为: " + inVideoMsg.getMediaId());
        render(outMsg);
    }

    /**
     * 实现父类抽方法，处理地址位置消息
     */
    protected void processInLocationMsg(InLocationMsg inLocationMsg) {
        OutTextMsg outMsg = new OutTextMsg(inLocationMsg);
        outMsg.setContent("已收到地理位置消息:" +
                "\nlocation_X = " + inLocationMsg.getLocation_X() +
                "\nlocation_Y = " + inLocationMsg.getLocation_Y() +
                "\nscale = " + inLocationMsg.getScale() +
                "\nlabel = " + inLocationMsg.getLabel());
        render(outMsg);
    }

    /**
     * 实现父类抽方法，处理链接消息
     * 特别注意：测试时需要发送我的收藏中的曾经收藏过的图文消息，直接发送链接地址会当做文本消息来发送
     */
    protected void processInLinkMsg(InLinkMsg inLinkMsg) {
        OutNewsMsg outMsg = new OutNewsMsg(inLinkMsg);
        outMsg.addNews("链接消息已成功接收", "链接使用图文消息的方式发回给你，还可以使用文本方式发回。点击图文消息可跳转到链接地址页面，是不是很好玩 :)", "http://mmbiz.qpic.cn/mmbiz/zz3Q6WSrzq1ibBkhSA1BibMuMxLuHIvUfiaGsK7CC4kIzeh178IYSHbYQ5eg9tVxgEcbegAu22Qhwgl5IhZFWWXUw/0", inLinkMsg.getUrl());
        render(outMsg);
    }

    /**
     * 实现父类抽方法，处理关注/取消关注消息
     */
    protected void processInFollowEvent(InFollowEvent inFollowEvent) {
        helpString(inFollowEvent);

    }

    /**
     * 实现父类抽方法，处理扫描带参数二维码事件
     */
    protected void processInQrCodeEvent(InQrCodeEvent inQrCodeEvent) {
        OutTextMsg outMsg = new OutTextMsg(inQrCodeEvent);
        outMsg.setContent("processInQrCodeEvent() 方法测试成功");
        render(outMsg);
    }

    /**
     * 实现父类抽方法，处理上报地理位置事件
     */
    protected void processInLocationEvent(InLocationEvent inLocationEvent) {
        OutTextMsg outMsg = new OutTextMsg(inLocationEvent);
        outMsg.setContent("processInLocationEvent() 方法测试成功");
        render(outMsg);
    }

    /**
     * 实现父类抽方法，处理自定义菜单事件
     */
    protected void processInMenuEvent(InMenuEvent inMenuEvent) {
//        OutTextMsg outMsg = new OutTextMsg(inMenuEvent);
//        outMsg.setContent("processInMenuEvent() 方法测试成功");
//        render(outMsg);
        System.out.println("=========------------=====" );

        String key = inMenuEvent.getEventKey();
        System.out.println("==============" + key);
        Record wMsg = wMessage(key);
        //返回列表信息
        if (wMsg != null) {
            String msgtype = (String) wMsg.get("msgtype"); // 回复文本类型
            String description = (String) wMsg.get("description"); // 关键字
            String url = (String) wMsg.get("url"); // 消息链接
            String picurl = (String) wMsg.get("picurl"); // 消息图片
            String title = (String) wMsg.get("title"); // 标题
            String content = (String) wMsg.get("content"); // 文本内容
            if(picurl !=null) {
                picurl=urls.substring(0,urls.length()-1)+  picurl;
            }
            // 文本消息
            if (msgtype.equals("text")) {
                OutTextMsg outMsg = new OutTextMsg(inMenuEvent);
                outMsg.setContent(content);
                render(outMsg);
                // 图文消息
            } else if (msgtype.equals("news")) {
                OutNewsMsg outMsg = new OutNewsMsg(inMenuEvent);
                outMsg.addNews(title, "", picurl, url);
                render(outMsg);
                // 语音消息
            } else {
                OutTextMsg outMsg = new OutTextMsg(inMenuEvent);
                outMsg.setContent("\t消息已成功接收，内容为： " + inMenuEvent.getEventKey() + "\n");
                render(outMsg);
            }
        }    else {
            OutTextMsg outMsg = new OutTextMsg(inMenuEvent);
            outMsg.setContent("欢迎光临");
            render(outMsg);
        }

    }

    /**
     * 实现父类抽方法，处理接收语音识别结果
     */
    protected void processInSpeechRecognitionResults(InSpeechRecognitionResults inSpeechRecognitionResults) {
        OutTextMsg outMsg = new OutTextMsg(inSpeechRecognitionResults);
        outMsg.setContent("processInSpeechRecognitionResults() 方法测试成功");
        render(outMsg);
    }

    /**
     * 罗列标题和关键字作为帮助消息
     *
     * @return String
     */
    public void helpString(InFollowEvent inFollowEvent) {
        List<Record> newlist;
        newlist = CacheKit.get("WxMessage", "WxMessage");
        if (newlist == null) {
            newlist = WxMessage.dao.findAlls("");
            //放入缓存
            CacheKit.put("WxMessage", "WxMessage", newlist);
        }
        for (int i = 0; i < newlist.size(); i++) {
            String msgtype = (String) newlist.get(i).get("msgtype"); // 回复文本类型
            String description = (String) newlist.get(i).get("description"); // 关键字
            String url = (String) newlist.get(i).get("url"); // 消息链接
            String picurl = (String) newlist.get(i).get("picurl"); // 消息图片
            String title = (String) newlist.get(i).get("title"); // 标题
            String content = (String) newlist.get(i).get("content"); // 文本内容
            String yxbz = (String) newlist.get(i).get("yxbz"); // 文本内容
            if (yxbz.equals("1")) {
                if (msgtype.equals("text")) {
                    OutTextMsg outMsg = new OutTextMsg(inFollowEvent);
                    outMsg.setContent(content);
                    render(outMsg);
                    // 图文消息
                } else if (msgtype.equals("news")) {
                    OutNewsMsg outMsg = new OutNewsMsg(inFollowEvent);
                    outMsg.addNews(title, "", picurl, url);
                    render(outMsg);
                    // 语音消息
                }
            }
        }
    }

    /**
     * 根据   msgContent 返回匹配的Record 信息
     *
     * @param msgContent
     * @return Record
     */
    public Record wMessage(String msgContent) {

        List<Record> newlist;
        newlist = CacheKit.get("WxMessage", "WxMessage");
        if (newlist == null) {
            newlist = WxMessage.dao.findAlls("");
            CacheKit.put("WxMessage", "WxMessage", newlist);
        }
        int j = 0;
        for (int i = 0; i < newlist.size(); i++) {
            if (msgContent.equalsIgnoreCase(String.valueOf(newlist.get(i).get("description")))) {
                j = i;
                System.out.print(j);
                break;
            } else {
                j = 99999999;
            }
        }
        if (j == 99999999) {
            return null;
        } else {
            return newlist.get(j);
        }
    }


    /**
     * 获取公众号菜单
     */
    public void getMenu() {
        ApiResult apiResult = MenuApi.getMenu();
        if (apiResult.isSucceed())
            renderText(apiResult.getJson());
        else
            renderText(apiResult.getErrorMsg());
    }


}






